<?php
	class CategoryModel extends Model{
		
		public $validate = array(
			array('cname','nonull','分类名不能为空',2,3),
			array('cname','minlen:1','分类名不能少于1个字符',2,3),
			array('cname','maxlen:20','分类名不能大于20个字符',2,3),
			array('pid','/^\d{1,5}$/','父类ID不能为空',2,3),
			array('cdesc','nonull','描述不能为空',2,3),
			array('cdesc','minlen:4','描述不能少于4个字符',2,3),
			array('cdesc','maxlen:20','描述不能大于20个字符',2,3)
		);
		
		/**
		 * 获得一个所有的数组结构的数组
		 */
		public function getTree(){
			//获得所有分类	
			$cates = $this->all();
			$tree = Data::tree($cates,'cname','cid','pid');
			return $tree;
		}
		
		/**
		 * 获得一个分类多维数组返回一个重组后的数组
		 * 得到他们的子级结构数组
		 * @return array
		 */
		 public function getMoreCateArr(){
		 	$newArr = array();
		 	$data = $this->where('is_show=1')->all();
		 	$topCate = $this->where('pid=0')->all();
			foreach($topCate as $cate){
				$newArr[] = $this->regroupCate($data, $cate);
			}
			return $newArr;
		 }
		 
		 /**
		  * 递归获得当前分类所有的子类并且压入到
		  * 他相应的数组中的key为son中
		  */
		  private function regroupCate($data,$cate){
		  	
		  	foreach($data as $d){
		  		if($d['pid'] == $cate['cid']){
					$cate['son'][] = $this->regroupCate($data, $d);
		  		}
		  	}
			return $cate;			
		  }
		 
		 
		 /**
		  * 获得当前分类 的所有分类
		  * 获得当前分类的cid   T
		  */
		  public function getFather($cid){
		  	$data = $this->all();
			$mbx = $this->_diguiFather($data, $cid);
			$mbx = array_reverse($mbx);
			foreach($mbx as $k=>$v){
				if(empty(trim($v['cname']))){
					unset($mbx[$k]);
				}
			}
			return $mbx;
		  }
		  
		 /**
		  * 递归获得当前分类的父分类
		  */
		 private function _diguiFather($data,$cid){
		 	$tmp = array();
			foreach($data as $key=>$val){
				if($val['cid'] == $cid){
					$tmp[] = $val;
					$tmp = array_merge($tmp,$this->_diguiFather($data, $val['pid']));
					
				}
			}
			return $tmp;
		 }
		
		
		/**
		 * 更新一个分类
		 */
		 public function upCategory(){
		 	if(!$this->create()) return false;
			if($this->update()){
				return true;
			}else{
				$this->error = '数据更新失败';
			}
		 }
		
		
		/**
		 * 添加分类方法
		 */
		 public function addCate(){
		 	if(!$this->create()) return false;
			if($this->add()){
				return true;
			}else{
				$this->error = '写入数据失败';
			}
		 }

		/**
		 * 获得一个pid为相应的CID的子类集
		 */
		 public function getSon($pid){
		 	//获得一个树形结构的数组
		 	$tree = $this->getTree();
			$cateSons = array();
			
			foreach($tree as $t){
				if($t['pid'] == $pid){
					$cateSons[] = $t;
				}
			}
			
			return $cateSons;
		 }
		
		/**
		 * 当前分类下面所有的子
		 * @return Array
		 */
		 public function getAllChild($cid){
			$tree = $this->getTree();
			$allChild = $this->getChild($tree,$cid);
			return $allChild;
		 }
		 
		 /**
		  * 递归查询当前所有的子类和孙子类
		  * @return Array
		  */
		  private function getChild($data,$pid){
		  	$arr = array();
			foreach($data as $v){
				if($v['pid'] == $pid){
					$arr[] = $v['cid'];
					$arr = array_merge($arr,$this->getChild($data,$v['cid'])); 
				}
			}
			return $arr;
		  }
		 
	}
